package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocal;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IApUserSearchService;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private IApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {

        //如果关键字为空 直接返回一个null
        if(dto==null|| StringUtils.isEmpty(dto.getSearchWords())){
            return null;
        }
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", dto.getSearchWords());

        //分页并且根据发布时间排序
        PageRequest pageRequest = PageRequest.of( dto.getPage().intValue() - 1, dto.getSize(), Sort.by(Sort.Direction.DESC, "publishTime"));
        Page<ApArticleSearch> searchPage = articleRepository.search(queryBuilder, pageRequest);

        //只返回列表就可以
        ResponseResult result = ResponseResult.okResult(searchPage.getContent());

        // 异步保存用户的搜索记录  1 启动类上添加注解   2 新建任务类 添加异步方法
        //向mongo中插入历史记录  谁 在什么时候 什么关键字
        apUserSearchService.saveSearchRecord(UserThreadLocal.get().getUserId(),dto.getSearchWords(),dto.getEquipmentId());

        return result;
    }
}
